<template>
  <view class="city-select-page">
    <!-- 导航栏区域 -->
    <view class="header">
      <view class="header-left">
        <u-icon name="arrow-left" size="40" color="#ffffff" @click="goBack"></u-icon>
      </view>
      <view class="header-title">选择城市</view>
      <view class="header-right">
        <view class="header-right-button"></view>
      </view>
    </view>
    <!-- 搜索交互区 -->
    <view class="search-bar">
      <image class="search-icon" src="/static/icons/search.png"></image>
      <input class="search-input" placeholder="请输入城市名" placeholder-style="color:#ccc" v-model="search" />
      <text class="search-btn">搜索</text>
    </view>
    <!-- 展示当前城市 -->
    <view class="current-city">当前城市：
      <view class="city-tag" @click="selectCity(currentCity)">{{ currentCity.name }}</view>
    </view>
    <!-- 内容展示区 -->
    <view class="content">
      <!-- 字母索引城市 -->
      <view class="section" v-for="group in filteredCityGroups" :key="group.letter">
        <text class="section-title">{{ group.letter }}</text>
        <view class="tag-group">
          <view class="city-tag" @click="selectCity(city)" v-for="city in group.cities" :key="city.id">
            <text class="city-tag-text">{{ city.name }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getCityList, getCurrentCity } from '@/api/partner.js'
import { mapGetters, mapState } from 'vuex';
export default {
  name: 'CitySelect',
  data() {
    return {
      search: '',
      cityGroups: [],
      currentCity: null,
      isLocating: true,
      locationError: ''
    }
  },
  async onLoad(options) {
    // 优先检查路由参数中的城市信息
    if (options.cityId && options.cityName) {
      this.currentCity = {
        id: options.cityId,
        name: options.cityName
      };
      console.log('使用路由参数城市数据:', this.currentCity);
      return;
    }
    await this.getCityData();
    this.CurrentCity();
    this.loadCachedCity();
  },
  computed: {
    isGroupChat() {
      return this.chatType === 'group';
    },
    ...mapGetters(['getUserInfo']),
    ...mapState({
      globalConfig: state => state.config,
      userLocation: state => state.location,
      userInfo: state => state.userInfo,
    }),
    filteredCityGroups() {
      if (!this.search) return this.cityGroups;

      const searchTerm = this.search.toLowerCase();
      return this.cityGroups.map(group => ({
        ...group,
        cities: group.cities.filter(city =>
          city.name.toLowerCase().includes(searchTerm)
        )
      })).filter(group => group.cities.length > 0);
    }
  },
  methods: {
    loadCachedCity() {
      // 确保城市数据已加载
      if (this.cityGroups.length === 0) {
        this.isLocating = false
        this.locationError = '城市数据加载中，请稍后重试'
        return
      }
      // 从store获取用户位置信息
      let userCityName = '';
      try {
        const userInfo = uni.getStorageSync('userInfo') || {};
        console.log('userInfo from storage:', userInfo);
        if (userInfo.city) {
          userCityName = userInfo.city;
        } else if (userInfo.location && userInfo.location.city) {
          userCityName = userInfo.location.city;
        }
      } catch (e) {
        console.error('Failed to get city from storage:', e);
      }

      if (userCityName) {
        // 与城市数据比对匹配城市信息
        this.matchCityFromStore(userCityName)
      } else {
        this.isLocating = false
        this.locationError = '未找到用户位置信息，请手动选择'
      }
    },
    matchCityFromStore(userCityName) {
      // 标准化城市名称（移除省/市后缀进行匹配）
      const normalizedUserCity = userCityName.replace(/[省市]/g, '')
      // 遍历城市列表匹配城市
      const allCities = this.cityGroups.flatMap(group => group.cities)
      // 优先精确匹配，再尝试模糊匹配（支持去除省/市后缀的匹配）
      const exactMatch = allCities.find(city =>
        city.name === userCityName || city.name === normalizedUserCity
      )
      fuzzyMatch = exactMatch || allCities.find(city =>
        userCityName.includes(city.name) ||
        normalizedUserCity.includes(city.name) ||
        city.name.includes(normalizedUserCity)
      )
      const fuzzyMatch = exactMatch || allCities.find(city =>
        userCityName.includes(city.name) || city.name.includes(userCityName)
      )

      if (fuzzyMatch) {
        this.currentCity = {
          id: fuzzyMatch.id,
          name: fuzzyMatch.name
        }
        this.isLocating = false
      } else {
        this.isLocating = false
        this.locationError = `未找到${userCityName}对应的城市，请手动选择`
      }
    },
    goBack() {
      uni.navigateBack();
    },
    async getCityData() {
      try {
        const res = await getCityList()
        console.log('API返回数据:', res);
        if (res.data.code === 1) {
          // 将对象转换为数组并按字母排序
          const cityEntries = Object.entries(res.data.data || {});
          cityEntries.sort((a, b) => a[0].localeCompare(b[0]));
          this.cityGroups = cityEntries.map(([letter, cities]) => ({ letter, cities }));
          console.log(this.cityGroups, 'cityGroups');
          // 设置当前城市
          if (this.cityGroups.length > 0 && this.cityGroups[0].cities.length > 0) {
            this.currentCity = this.cityGroups[0].cities[0];
          }
        }
      } catch (error) {
        uni.showToast({ title: '获取城市数据失败', icon: 'none' })
      }
    },
    // 获取当前城市
    async CurrentCity() {
      try {
        const res = await getCurrentCity({
          long: this.userLocation.longitude,
          lat: this.userLocation.latitude
        })
        console.log('获取当前城市:', res);
        if (res.data.code == 1) {
          this.currentCity = res.data.data || null;
          console.log('当前城市:', this.currentCity);

        }
      } catch (error) {
        uni.showToast({ title: '获取当前城市失败', icon: 'none' })
      }
    },
    async selectCity(city) {
      if (!city || !city.id) return
      const eventChannel = this.getOpenerEventChannel()
      this.currentCity = city;
      // 获取城市经纬度
      try {
        // 更新store位置信息
        this.$store.commit('SET_LOCATION', {
          name: city.name,
          id: city.id,
        });
      } catch (error) {
        console.error('获取城市坐标失败:', error);
        // 更新store位置信息（不含坐标）
        this.$store.commit('SET_LOCATION', {
          city: city.name,
          address: city.name
        });
      }
      eventChannel.emit('selectCity', {
        area_id: city.id,
        city_name: city.name
      })
      // 保存城市信息到本地缓存
      uni.setStorageSync('selectedCity', {
        id: city.id,
        name: city.name
      })
      uni.navigateBack()
    }
  }
}
</script>

<style scoped>
.city-select-page {
  background-color: #1a191e;
  min-height: 100vh;
}

.status-bar {
  width: 750rpx;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
  padding-top: 120rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #fff;
}

.header-right-button {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 30rpx;
  padding: 10rpx 20rpx;
  display: flex;
  align-items: center;
  backdrop-filter: blur(10rpx);
}


.search-bar {
  display: flex;
  align-items: center;
  height: 80rpx;
  background-color: #222;
  margin: 20rpx 30rpx;
  border-radius: 40rpx;
}

.search-icon {
  width: 40rpx;
  height: 40rpx;
  margin-left: 20rpx;
}

.search-input {
  flex: 1;
  height: 70rpx;
  color: #fff;
  font-size: 28rpx;
  margin: 0 20rpx;
}

.search-btn {
  width: 120rpx;
  text-align: center;
  color: #fff;
  font-size: 28rpx;
  margin-right: 20rpx;
}

.content {
  padding: 0 30rpx;
}

.section-title {
  font-size: 32rpx;
  color: #fff;
  margin: 30rpx 0 10rpx;
}

.tag-group {
  display: flex;
  flex-wrap: wrap;
}

.city-tag {
  background-color: #222;
  border-radius: 40rpx;
  padding: 16rpx 24rpx;
  margin: 10rpx;
  /* 边框阴影 */
  /* border: 1px solid #fff; */
}

.no-results {
  text-align: center;
  padding: 40rpx;
  color: #999;
  font-size: 28rpx;
}

.city-tag-text {
  font-size: 28rpx;
  color: #fff;
}

.loading-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx;
}

.loading-text {
  margin-left: 10rpx;
  color: #999;
  font-size: 28rpx;
}

.current-city {
  display: flex;
  align-items: center;
  color: #fff;
  padding: 15rpx;
  margin-bottom: 20rpx;
}

.city-tag-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 10rpx;
}
</style>
